﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Billing
{
    public class CloneSerializableObject
    {
        public static object Clone(object obj)
        {
            if (obj == null)
                throw new System.NullReferenceException("object is Null");

            if (!obj.GetType().IsSerializable)
                throw new System.Runtime.Serialization.SerializationException("is not marked serializable");

            MemoryStream ms = new MemoryStream();
            try
            {
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(ms, obj);
                ms.Position = 0;
                return bf.Deserialize(ms);
            }
            catch (System.Runtime.Serialization.SerializationException ex)
            { throw ex; }
            catch (Exception ex)
            { throw ex; }
            finally
            {
                ms.Dispose();
                ms = null;
                GC.Collect();
            }
        }
    }
}
